package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器
@Component//放入容器
public class LoginCheckInterceptor implements HandlerInterceptor {

    //在进入controller之前进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //验证用户是否登录了
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");
        if (employee == null) {
            //非法访问，返回错误
            System.out.println("用户未登录，非法访问");

            //返回错误信息，提示前端
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");//组装对象
            String json = new ObjectMapper().writeValueAsString(resultInfo);//转换json
            response.getWriter().write(json); //返回json对象
            return false;//禁止通行
        } else {
            //正常放行
            //将employee放入ThreadLocal
            EmployeeHolder.set(employee);
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
